{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c089d6d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "from Read_sample_image import read_pic\n",
    "import torchvision as tv\n",
    "import torch\n",
    "from torch import nn\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b3a1b7fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "IMG_PATH = r\"D:\\MathmaticModel\\Pic_data\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c45c8080",
   "metadata": {},
   "outputs": [],
   "source": [
    "def corr2d(X, K):\n",
    "    h, w = K.shape\n",
    "    Y = torch.zeros((X.shape[0]- h + 1, X.shape[1]- w + 1))\n",
    "    for i in range(Y.shape[0]):\n",
    "        for j in range(Y.shape[1]):\n",
    "            Y[i, j] = (X[i:i + h, j:j + w] * K).sum()\n",
    "            \n",
    "    return Y\n",
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "1da5d9ae",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
       "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.ones((6, 8))\n",
    "X[:, 2:6] = 0\n",
    "K = torch.tensor([[1.0,-1.0]])\n",
    "Y = corr2d(X, K)\n",
    "Y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "faebbe8e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, loss 7.777\n",
      "epoch 4, loss 2.080\n",
      "epoch 6, loss 0.667\n",
      "epoch 8, loss 0.242\n",
      "epoch 10, loss 0.094\n"
     ]
    }
   ],
   "source": [
    "conv2d = nn.Conv2d(1,1, kernel_size=(1, 2), bias=False)\n",
    " # 这个二维卷积层使用四维输入和输出格式（批量大小、通道、高度、宽度），\n",
    "# 其中批量大小和通道数都为1\n",
    "X = X.reshape((1, 1, 6, 8))\n",
    "Y = Y.reshape((1, 1, 6, 7))\n",
    "lr = 3e-2 # 学习率\n",
    "for i in range(10):\n",
    "    Y_hat = conv2d(X)\n",
    "    l = (Y_hat- Y) ** 2\n",
    "    conv2d.zero_grad()\n",
    "    l.sum().backward()\n",
    " # 迭代卷积核\n",
    "    conv2d.weight.data[:]-= lr * conv2d.weight.grad\n",
    "    if (i + 1) % 2 == 0:\n",
    "        print(f'epoch {i+1}, loss {l.sum():.3f}')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ff7d19ba",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621],\n",
       "          [ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621],\n",
       "          [ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621],\n",
       "          [ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621],\n",
       "          [ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621],\n",
       "          [ 0.0621,  1.0199,  0.0000,  0.0000,  0.0000, -0.9579,  0.0621]]]],\n",
       "       grad_fn=<ConvolutionBackward0>)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conv2d(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "48f25dda",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.0199068, -0.9578566]], dtype=float32)"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "2faeb192",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[[1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "          [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "          [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "          [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "          [1., 1., 0., 0., 0., 0., 1., 1.],\n",
       "          [1., 1., 0., 0., 0., 0., 1., 1.]]]])"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "4ac68570",
   "metadata": {},
   "outputs": [],
   "source": [
    "arr = np.array(conv2d.weight.data.reshape((1,2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "77b98d04",
   "metadata": {},
   "outputs": [],
   "source": [
    " nn.Conv2d?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
